package com.h3c.nem.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.h3c.nem.client.DataCenterFeignClient;
import com.h3c.nem.dto.SdUserDTO;
import com.h3c.nem.entity.SdAllWorker;
import com.h3c.nem.entity.SdUser;
import com.h3c.nem.enums.AutoOpTypeEnum;
import com.h3c.nem.mapper.SdAllWorkerMapper;
import com.h3c.nem.mapper.SdDeptMapper;
import com.h3c.nem.mapper.SdUserMapper;
import com.h3c.nem.service.CommService;
import com.h3c.nem.service.ISdUserService;
import com.h3c.nem.utils.AppBusinessException;
import com.h3c.nem.utils.BusiEnumDefine;
import com.h3c.nem.utils.CommonUtil;
import com.h3c.nem.utils.InitExampleOrderByUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

//import org.apache.commons.lang3.StringUtils;

/**
 * Copyright (C), 2020-2020, h3c
 * FileName: SdUserServiceImpl
 *
 * @Author: l22886
 * @Date: 2022-01-19
 * Description: sd_user serviceImpl
 * Version: 1.0
 */
@Slf4j
@Service
public class SdUserServiceImpl extends ServiceImpl<SdUserMapper, SdUser> implements ISdUserService {
    @Resource
    private SdUserMapper sdUserMapper;
    @Autowired
    private CommService commService;
    @Autowired
    DataCenterFeignClient dataCenterFeignClient;
    @Autowired
    SdAllWorkerMapper sdAllWorkerMapper;
    @Autowired
    SdDeptMapper sdDeptMapper;

    private static final String deptRedis = "nem_dept_";

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * @title: selectFuzzyByDto
     * @description: 模糊查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<SdUserDTO> selectFuzzyByDto(SdUserDTO dto) {
        //List<SdUser> list = sdUserMapper.selectByExample(initFuzzyExample(dto));

        QueryWrapper<SdUser> queryWrapper = new QueryWrapper<SdUser>();

        if(dto.getUserId()!=null&&!dto.getUserId().isEmpty()){
            List<String> userIdList= Arrays.asList(dto.getUserId().split(","));
            queryWrapper.in("user_id",userIdList);
        }
        if (!dto.getUserRole().isEmpty() && dto.getUserRole() != null) {
            queryWrapper.in("user_role",dto.getUserRole());
        }
//        if(dto.getUserRole()!=null){
//
//        }
        List<SdUser> sdUsersList=sdUserMapper.selectList(queryWrapper);
        //List<SdUser> list = sdUserMapper.queryListByFuzzy(JSONObject.parseObject(JSONObject.toJSONString(dto),SdUser.class));
        return JSONArray.parseArray(JSONArray.toJSONString(sdUsersList), SdUserDTO.class);
    }

    /**
     * @title: selectByDto
     * @description: 精确查询操作
     * @params: [ dto ]
     * @return: java.util.List
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    @Override
    public List<SdUserDTO> selectByDto(SdUserDTO dto) {
        //List<SdUser> list = sdUserMapper.selectByExample(initExample(dto));
        List<SdUser> list = sdUserMapper.queryList(JSONObject.parseObject(JSONObject.toJSONString(dto),SdUser.class));
        return JSONArray.parseArray(JSONArray.toJSONString(list), SdUserDTO.class);
    }

    /**
     * @title: updateDto
     * @description: 修改操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-01-26
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public Integer updateDto(SdUserDTO dto) {
        if (null != dto && null != dto.getUserId() && !"".equals(dto.getUserId())) {
            String userRole=dto.getUserRole();
            String userId=dto.getUserId();
            SdUser sdUserOld = sdUserMapper.selectOne(new QueryWrapper<SdUser>().eq("user_id", userId));
            String oldUserRole=sdUserOld.getUserRole();
            if(!Objects.equals(oldUserRole, userRole)){
//                List<SdDept> sdDepts= sdDeptMapper.selectList(new QueryWrapper<SdDept>().like("bp_user_id",userId).or()
//                        .like("dept_manager_id",userId).or()
//                        .like("contactor_id",userId));
               /* if(oldUserRole==BusiEnumDefine.USER_ROLE_BP||oldUserRole==BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR||oldUserRole==BusiEnumDefine.USER_ROLE_DEPT_MANAGER){//别的角色可改
                    String authDeptS = redisTemplate.opsForValue().get(deptRedis + userId);
                    if (!StringUtils.isEmpty(authDeptS)) {
                        throw new AppBusinessException("[工号：" + userId + "]的用户已经被设置为某些部门的HRBP、部门接口人、部门主管，不允许修改其当前角色！");
                    }
                }*/
                dto.setUserRole(userRole);
            }
//            if(dto.getUserRole()==BusiEnumDefine.USER_ROLE_BP||dto.getUserRole()==BusiEnumDefine.USER_ROLE_GBBZ){
//                if(!StringUtils.isEmpty(dto.getTeacherFlag())){
//                    dto.setTeacherFlag(dto.getTeacherFlag());
//                }
//            }
            dto.setOperatorId(commService.getLoginUserNameAndId());
            dto.setOperateTime(new Date());
            Integer n= sdUserMapper.updateSdUser(JSONObject.parseObject(JSON.toJSONString(dto), SdUser.class));
            commService.recordAuthChangeLog("sd_user", AutoOpTypeEnum.UPDATE,JSONObject.toJSONString(dto),"通过界面操作更改用户");
            Map<String, Object> dataCacheMap = CommService.dataCacheMap;
            dataCacheMap.remove(BusiEnumDefine.DOMAIN_ACCT_PREFIX + sdUserOld.getDomainAccount());

            return n;
        } else {
            return 0;
        }
    }

    /**
     * @title: deleteDto
     * @description: 删除操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-01-19* @version: 1.0
     * @author: l22886
     */
    @Override
    public Integer deleteDto(SdUserDTO dto) {
        //if (null != dto && null != dto.getId() && !"".equals(dto.getId())) {
            Map<String, Object> dataCacheMap = CommService.dataCacheMap;
            dataCacheMap.remove(BusiEnumDefine.DOMAIN_ACCT_PREFIX + dto.getDomainAccount());
            return sdUserMapper.deleteSdUser(JSONObject.parseObject(JSON.toJSONString(dto), SdUser.class));

            //return sdUserMapper.deleteByPrimaryKey(dto.getId());
        //} else {
        //    return 0;
        //}
    }


    /**
     * @title: initFuzzyExample
     * @description: 初始化 模糊查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    private Example initFuzzyExample(SdUserDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(SdUser.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getUserId() && !"".equals(dto.getUserId())) {
                criteriaName.andLike("UserId", "%" + dto.getUserId() + "%");
            }
            if (null != dto.getDomainAccount() && !"".equals(dto.getDomainAccount())) {
                criteriaName.andLike("DomainAccount", "%" + dto.getDomainAccount() + "%");
            }
            if (null != dto.getUserName() && !"".equals(dto.getUserName())) {
                criteriaName.andLike("UserName", "%" + dto.getUserName() + "%");
            }
            if (null != dto.getPhoneNo() && !"".equals(dto.getPhoneNo())) {
                criteriaName.andLike("PhoneNo", "%" + dto.getPhoneNo() + "%");
            }
            if (null != dto.getEmail() && !"".equals(dto.getEmail())) {
                criteriaName.andLike("Email", "%" + dto.getEmail() + "%");
            }
            if (null != dto.getUserRole() && !"".equals(dto.getUserRole())) {
                criteriaName.andLike("UserRole", "%" + dto.getUserRole() + "%");
            }
            if (null != dto.getDeptSystem() && !"".equals(dto.getDeptSystem())) {
                criteriaName.andLike("DeptSystem", "%" + dto.getDeptSystem() + "%");
            }
            if (null != dto.getOperateTime() && !"".equals(dto.getOperateTime())) {
                criteriaName.andLike("OperateTime", "%" + dto.getOperateTime() + "%");
            }
            if (null != dto.getOperatorId() && !"".equals(dto.getOperatorId())) {
                criteriaName.andLike("OperatorId", "%" + dto.getOperatorId() + "%");
            }
            if (null != dto.getCreatorId() && !"".equals(dto.getCreatorId())) {
                criteriaName.andLike("CreatorId", "%" + dto.getCreatorId() + "%");
            }
        }
        return example;
    }

    /**
     * @title: initExample
     * @description: 初始化 精确查询 example
     * @params: [ dto ]
     * @return: tk.mybatis.mapper.entity.Example
     * @createTime: 2022-01-19
     * @version: 1.0
     * @author: l22886
     */
    private Example initExample(SdUserDTO dto) {
        Example example = InitExampleOrderByUtils.initExampleOrderBy(SdUser.class, dto.getOrderBy());
        Example.Criteria criteriaName = example.createCriteria();
        if (null != dto) {
            if (null != dto.getUserId() && !"".equals(dto.getUserId())) {
                criteriaName.andEqualTo("UserId", dto.getUserId());
            }
            if (null != dto.getDomainAccount() && !"".equals(dto.getDomainAccount())) {
                criteriaName.andEqualTo("DomainAccount", dto.getDomainAccount());
            }
            if (null != dto.getUserName() && !"".equals(dto.getUserName())) {
                criteriaName.andEqualTo("UserName", dto.getUserName());
            }
            if (null != dto.getPhoneNo() && !"".equals(dto.getPhoneNo())) {
                criteriaName.andEqualTo("PhoneNo", dto.getPhoneNo());
            }
            if (null != dto.getEmail() && !"".equals(dto.getEmail())) {
                criteriaName.andEqualTo("Email", dto.getEmail());
            }
            if (null != dto.getUserRole() && !"".equals(dto.getUserRole())) {
                criteriaName.andEqualTo("UserRole", dto.getUserRole());
            }
            if (null != dto.getDeptSystem() && !"".equals(dto.getDeptSystem())) {
                criteriaName.andEqualTo("DeptSystem", dto.getDeptSystem());
            }
            if (null != dto.getOperateTime() && !"".equals(dto.getOperateTime())) {
                criteriaName.andEqualTo("OperateTime", dto.getOperateTime());
            }
            if (null != dto.getOperatorId() && !"".equals(dto.getOperatorId())) {
                criteriaName.andEqualTo("OperatorId", dto.getOperatorId());
            }
            if (null != dto.getCreatorId() && !"".equals(dto.getCreatorId())) {
                criteriaName.andEqualTo("CreatorId", dto.getCreatorId());
            }
        }
        return example;
    }

    /**
     * @title: insertDto
     * @description: 插入操作
     * @params: [ dto ]
     * @return: Integer
     * @createTime: 2022-01-25
     * @version: 1.0
     * @author:
     */
    @Override
    public Integer insertDto(SdUserDTO dto) {
        String userId=dto.getUserId();
        if(!userId.equals("")){
            SdUser checkIdUser = sdUserMapper.selectById(dto.getUserId());
            if(!ObjectUtils.isEmpty(checkIdUser)){
                throw new AppBusinessException("员工号已存在，请重新输入");
            }
        }else {
            throw new AppBusinessException("请添加需要设置的员工工号！");
        }
        SdAllWorker user = commService.getAllWorkerDoFromLocalCache(userId);
        if(user!=null){
            dto.setUserName(user.getWorkerName());
            dto.setDomainAccount(user.getDomainAccount());
            if(!StringUtils.isEmpty(user.getEmail())){
                dto.setEmail(user.getEmail());
            }else{
                String basicInfo=dataCenterFeignClient.queryWorkerBasicInfo("{\"empCode\":\""+userId+"\"}", commService.getEosToken());//正式员工
                JSONObject basicInfoJson=JSONObject.parseObject(basicInfo);
                List<Map<String,String>>workerList= (List<Map<String,String>>)basicInfoJson.get("data");
                if(workerList.size()>0&&!StringUtils.isEmpty(workerList.get(0).get("email"))){
                    dto.setEmail(workerList.get(0).get("email"));
                }else {//存在没有邮箱的员工
                    dto.setEmail(dto.getDomainAccount()+"@h3c.com");
                }
            }
        }else{
            Map<String, String> cooWorkerMap = commService.queryCooperativeWorker(userId);
            if(cooWorkerMap!=null){
                dto.setUserName(cooWorkerMap.get("emp_name"));
                dto.setDomainAccount(cooWorkerMap.get("domain_account"));
                dto.setEmail(cooWorkerMap.get("email"));
                //是合作员工，同时加入sdAllWorker
                SdAllWorker sdAllWorker = new SdAllWorker();
                    sdAllWorker.setWorkerId(cooWorkerMap.get("emp_code"));
                    sdAllWorker.setWorkerName(cooWorkerMap.get("emp_name"));
                    sdAllWorker.setDomainAccount(cooWorkerMap.get("domain_account"));
                    String directDeptId="";
                    if(!StringUtils.isEmpty(cooWorkerMap.get("dept1_code"))){
                        sdAllWorker.setDept1id(Integer.parseInt(cooWorkerMap.get("dept1_code")));
                        directDeptId=cooWorkerMap.get("dept1_code");
                    }
                    if(!StringUtils.isEmpty(cooWorkerMap.get("dept2_code"))){
                        sdAllWorker.setDept2id(Integer.parseInt(cooWorkerMap.get("dept2_code")));
                        directDeptId=cooWorkerMap.get("dept2_code");
                    }
                    if(!StringUtils.isEmpty(cooWorkerMap.get("dept3_code"))){
                        sdAllWorker.setDept3id(Integer.parseInt(cooWorkerMap.get("dept3_code")));
                        directDeptId=cooWorkerMap.get("dept3_code");
                    }
                    if(!StringUtils.isEmpty(cooWorkerMap.get("dept4_code"))){
                        sdAllWorker.setDept4id(Integer.parseInt(cooWorkerMap.get("dept4_code")));
                        directDeptId=cooWorkerMap.get("dept3_code");
                    }
                    sdAllWorker.setDirectDeptId(Integer.parseInt(directDeptId));
                    if(!StringUtils.isEmpty(cooWorkerMap.get("display_name"))){
                        sdAllWorker.setDisplayName(cooWorkerMap.get("display_name"));
                    }   if(!StringUtils.isEmpty(cooWorkerMap.get("email"))){
                        sdAllWorker.setEmail(cooWorkerMap.get("email"));
                    }
                    sdAllWorker.setSyncTime(new Date());
                    sdAllWorker.setWorkerType(2);//合作员工
                sdAllWorkerMapper.insertSdAllWorker(sdAllWorker);
                commService.addAllWorkerDoToLocalCache(cooWorkerMap.get("emp_code"), sdAllWorker);
                log.info("加入合作员工："+cooWorkerMap.get("emp_code")+"至人员总表。");
                
            }else {
                throw new AppBusinessException("未查询到当前员工信息！");
            }
        }
//        if(dto.getUserRole()==BusiEnumDefine.USER_ROLE_BP||dto.getUserRole()==BusiEnumDefine.USER_ROLE_GBBZ){
//            if(!StringUtils.isEmpty(dto.getTeacherFlag())){
//                dto.setTeacherFlag(dto.getTeacherFlag());
//            }
//        }
        dto.setCreatorId(commService.getLoginUserNameAndId());
        dto.setOperatorId(commService.getLoginUserNameAndId());
        dto.setOperateTime(new Date());
        for (String role : dto.getUserRole().split(",")) {
            if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_TEACHER_MANAGER){
                dto.setTeacherFlag(1);
            }
        }
        Integer n=sdUserMapper.insertSdUser(JSONObject.parseObject(JSON.toJSONString(dto), SdUser.class));
        //日志
        commService.recordAuthChangeLog("sd_user", AutoOpTypeEnum.ADD,JSONObject.toJSONString(dto),"通过界面操作添加用户");
        Map<String, Object> dataCacheMap = CommService.dataCacheMap;
        dataCacheMap.remove(BusiEnumDefine.DOMAIN_ACCT_PREFIX + dto.getDomainAccount());
        return n;
    }

    /**
     * @title: importUserRoleList
     * @description: 用户权限导入
     * @params: [ List<SdUserDTO> ]
     * @return: JSONObject
     * @createTime: 2022-01-26
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public Integer importUserRoleList(MultipartFile file) {
        String fileContent = commService.parseExcelByTemplate("USER_ROLE_IMPORT", file);
        JSONArray jsonArray = JSONArray.parseArray(fileContent);
        // List<SdUserDTO> sdUserDTOS = JSONArray.parseArray(fileContent, SdUserDTO.class);
        List<SdUserDTO> sdUserDTOSHave = selectFuzzyByDto(new SdUserDTO());//数据库中已存在的用户
        List<SdUserDTO> sdUsersDTOInsert=new ArrayList<>();//新增
        List<SdUserDTO> sdUsersdDTOUpdate=new ArrayList<>();//更新
        List<String> userIdList=new ArrayList<>();
        sdUserDTOSHave.forEach(sdUserDTO -> userIdList.add(sdUserDTO.getUserId()));
        List<SdUserDTO> sdUserDTOS=new ArrayList<>();
        int i=1;
        for (Object jsonObj : jsonArray) {
            i++;
            JSONObject jsonObject = JSONObject.parseObject(jsonObj.toString());
            //SdUserDTO sdUserDTO = JSONObject.parseObject(jsonObject.toJSONString(), SdUserDTO.class);

            SdUserDTO sdUserDTO=new SdUserDTO();
            String userId=jsonObject.get("userId").toString();
            SdAllWorker sdAllWorker=new SdAllWorker();
            if(!StringUtils.isEmpty(userId)){
                sdAllWorker = sdAllWorkerMapper.selectOne(new QueryWrapper<SdAllWorker>().eq("worker_id", userId));
                if (!StringUtils.isEmpty(sdAllWorker)) {
                    sdUserDTO.setUserId(userId);
                }else {
                    throw new AppBusinessException("系统中不存在工号："+userId+"用户！");
                }
            }  else {
                throw new AppBusinessException("第"+i+"行的用户工号为空！");
            }

            String basicInfo=dataCenterFeignClient.queryWorkerBasicInfo("{\"empCode\":\""+userId+"\"}", commService.getEosToken());
            JSONObject basicInfoJson=JSONObject.parseObject(basicInfo);
            List<Map<String,String>>basicInfoList= (List<Map<String,String>>)basicInfoJson.get("data");

            String domainAccount=jsonObject.get("domainAccount").toString();
            if(!StringUtils.isEmpty(domainAccount)){
                SdUser sdUser = sdUserMapper.selectOne(new QueryWrapper<SdUser>().eq("domain_account", domainAccount));
                if(sdUser!=null&& !sdUser.getUserId().equals(userId)){
                    throw new AppBusinessException("第"+i+"行工号："+userId+"用户的域账号与他人冲突,可清空后由系统自动配置！");
                }else {
                    sdUserDTO.setDomainAccount(domainAccount);
                }
            }else {
                sdUserDTO.setDomainAccount(basicInfoList.get(0).get("domain_account"));

            }

            String userName=jsonObject.get("userName").toString();
            if (null != userName && !"".equals(userName)) {
                sdUserDTO.setUserName(userName);
            }else{
                sdUserDTO.setUserName(basicInfoList.get(0).get("emp_name"));
            }
            //邮箱
            String email= jsonObject.get("email").toString();
            if (null != email && !"".equals(email)) {
                boolean isEmail = CommonUtil.checkEmail(email);
                if (!isEmail) {
                    throw new AppBusinessException("第"+i+"行,工号："+userId+"的邮箱格式有误，可清空后重新导入，由系统自动配置！");
                }else {
                    sdUserDTO.setEmail(email);
                }
            }else{
//                sdUserDTO.setEmail(basicInfoList.get(0).get("email"));
                sdUserDTO.setEmail(sdAllWorker.getEmail());

            }

            String userRoleCh = jsonObject.get("userRoleCh").toString();
            if(!StringUtils.isEmpty(userRoleCh)){
                String userRole=CommonUtil.getUserRoleCh(userRoleCh);
                sdUserDTO.setUserRole(userRole);
            }else {
               /* if(BusiEnumDefine.USER_ROLE_CEO==userRole||BusiEnumDefine.USER_ROLE_CHRO==userRole||BusiEnumDefine.USER_ROLE_SALARY_CHARGER==userRole){
                    SdUser sdUser = sdUserMapper.selectOne(new QueryWrapper<SdUser>().eq("user_role", userRole));
                    if(!StringUtils.isEmpty(sdUser)){
                        throw new AppBusinessException("当前设置的用户角色已经存在，请设置该用户为其他角色！");
                    }
                }else {*/
                throw new AppBusinessException("请正确填写工号："+userId+"的权限角色！");
                    //}
            }

            Date currentTime = new Date();
            sdUserDTO.setOperateTime(currentTime);
            sdUserDTO.setOperatorId(commService.getLoginUserNameAndId());
            if(!userIdList.contains(jsonObject.get("userId").toString())){
                sdUserDTO.setCreatorId(commService.getLoginUserNameAndId());
            }
            sdUserDTOS.add(sdUserDTO);
        }

        for (SdUserDTO sdUserDTO : sdUserDTOS) {
            if(userIdList.contains(sdUserDTO.getUserId())){
                sdUsersdDTOUpdate.add(sdUserDTO);
            }else {
                sdUsersDTOInsert.add(sdUserDTO);
            }
        }
        List<SdUser> sdUserInsertList= JSONArray.parseArray(JSONArray.toJSONString(sdUsersDTOInsert), SdUser.class);
        List<SdUser> sdUserUpdateList= JSONArray.parseArray(JSONArray.toJSONString(sdUsersdDTOUpdate), SdUser.class);

        int updateNum=0;
        int insertNum=0;
        //日志
        for (SdUser sdUser : sdUserUpdateList) {
            updateNum=updateNum+ sdUserMapper.updateSdUser(sdUser);
            commService.recordAuthChangeLog("sd_user", AutoOpTypeEnum.UPDATE,JSONObject.toJSONString(sdUser),"通过导入更新用户");
        }
        for (SdUser sdUser : sdUserInsertList) {
            insertNum=insertNum+ sdUserMapper.insertSdUser(sdUser);
            commService.recordAuthChangeLog("sd_user", AutoOpTypeEnum.UPDATE,JSONObject.toJSONString(sdUser),"通过导入新建用户");
        }
        return updateNum+insertNum;
    }

    /**
     * @title: importUserNew
     * @description: 用户权限导入
     * @params: [ List<SdUserDTO> ]
     * @return: JSONObject
     * @createTime: 2022-01-26
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public Integer importUserNew(MultipartFile file) {
        String fileContent = commService.parseExcelByTemplate("USER_ROLE_IMPORT", file);
        JSONArray jsonArray = JSONArray.parseArray(fileContent);
        // List<SdUserDTO> sdUserDTOS = JSONArray.parseArray(fileContent, SdUserDTO.class);
        List<SdUserDTO> sdUserDTOSHave = selectFuzzyByDto(new SdUserDTO());//数据库中已存在的用户
        List<SdUserDTO> sdUsersDTOInsert=new ArrayList<>();//新增
        List<SdUserDTO> sdUsersdDTOUpdate=new ArrayList<>();//更新
        List<String> userIdList=new ArrayList<>();
        sdUserDTOSHave.forEach(sdUserDTO -> userIdList.add(sdUserDTO.getUserId()));
        List<SdUserDTO> sdUserDTOS=new ArrayList<>();
        int i=1;
        for (Object jsonObj : jsonArray) {
            i++;
            JSONObject jsonObject = JSONObject.parseObject(jsonObj.toString());
            //SdUserDTO sdUserDTO = JSONObject.parseObject(jsonObject.toJSONString(), SdUserDTO.class);

            SdUserDTO sdUserDTO=new SdUserDTO();
            String userId=jsonObject.get("userId").toString();
            SdAllWorker sdAllWorker=new SdAllWorker();


            //
            //先查缓存，缓存没有，再查数据库,；
            SdAllWorker user = commService.getAllWorkerDoFromLocalCache(userId);
            if(user!=null){
            }else{
                user= sdAllWorkerMapper.selectOne(new QueryWrapper<SdAllWorker>().eq("worker_id", userId));
            }
            if(user!=null){
                commService.addAllWorkerDoToLocalCache(userId, user);//数据库直接添加的allWorker在这一步加入缓存
                sdUserDTO.setUserId(userId);
                sdUserDTO.setUserName(user.getWorkerName());
                sdUserDTO.setDomainAccount(user.getDomainAccount());
                if(!StringUtils.isEmpty(user.getEmail())){
                    sdUserDTO.setEmail(user.getEmail());
                }else{
                    String basicInfo=dataCenterFeignClient.queryWorkerBasicInfo("{\"empCode\":\""+userId+"\"}", commService.getEosToken());//正式员工
                    JSONObject basicInfoJson=JSONObject.parseObject(basicInfo);
                    List<Map<String,String>>workerList= (List<Map<String,String>>)basicInfoJson.get("data");
                    if(workerList.size()>0&&!StringUtils.isEmpty(workerList.get(0).get("email"))){
                        sdUserDTO.setEmail(workerList.get(0).get("email"));
                    }else {//存在没有邮箱的员工
                        throw new AppBusinessException("中台缺少工号："+userId+"的邮箱，请填写后导入或联系管理员！");
                    }
                }
            }else{
                Map<String, String> cooWorkerMap = commService.queryCooperativeWorker(userId);
                if(cooWorkerMap!=null){
                    sdUserDTO.setUserId(userId);
                    sdUserDTO.setUserName(cooWorkerMap.get("emp_name"));
                    sdUserDTO.setDomainAccount(cooWorkerMap.get("domain_account"));
                    sdUserDTO.setEmail(cooWorkerMap.get("email"));
                    //是合作员工，同时加入sdAllWorker
                    SdAllWorker sdAllWorker1 = new SdAllWorker();
                    sdAllWorker1.setWorkerId(cooWorkerMap.get("emp_code"));
                    sdAllWorker1.setWorkerName(cooWorkerMap.get("emp_name"));
                    sdAllWorker1.setDomainAccount(cooWorkerMap.get("domain_account"));
                    String directDeptId="";
                    if(!StringUtils.isEmpty(cooWorkerMap.get("dept1_code"))){
                        sdAllWorker1.setDept1id(Integer.parseInt(cooWorkerMap.get("dept1_code")));
                        directDeptId=cooWorkerMap.get("dept1_code");
                    }
                    if(!StringUtils.isEmpty(cooWorkerMap.get("dept2_code"))){
                        sdAllWorker1.setDept2id(Integer.parseInt(cooWorkerMap.get("dept2_code")));
                        directDeptId=cooWorkerMap.get("dept2_code");
                    }
                    if(!StringUtils.isEmpty(cooWorkerMap.get("dept3_code"))){
                        sdAllWorker1.setDept3id(Integer.parseInt(cooWorkerMap.get("dept3_code")));
                        directDeptId=cooWorkerMap.get("dept3_code");
                    }
                    if(!StringUtils.isEmpty(cooWorkerMap.get("dept4_code"))){
                        sdAllWorker1.setDept4id(Integer.parseInt(cooWorkerMap.get("dept4_code")));
                        directDeptId=cooWorkerMap.get("dept3_code");
                    }
                    sdAllWorker1.setDirectDeptId(Integer.parseInt(directDeptId));
                    if(!StringUtils.isEmpty(cooWorkerMap.get("display_name"))){
                        sdAllWorker1.setDisplayName(cooWorkerMap.get("display_name"));
                    }   if(!StringUtils.isEmpty(cooWorkerMap.get("email"))){
                        sdAllWorker1.setEmail(cooWorkerMap.get("email"));
                    }
                    sdAllWorker1.setSyncTime(new Date());
                    sdAllWorker1.setWorkerType(2);//合作员工
                    sdAllWorkerMapper.insertSdAllWorker(sdAllWorker1);
                    commService.addAllWorkerDoToLocalCache(cooWorkerMap.get("emp_code"), sdAllWorker1);
                    log.info("加入合作员工："+cooWorkerMap.get("emp_code")+"至人员总表。");

                }else {
                    continue;
                }
            }
            //


            String userRoleCh = jsonObject.get("userRoleCh").toString();
            if(!StringUtils.isEmpty(userRoleCh)){
                String role = CommonUtil.getUserRoleCh(userRoleCh);
                sdUserDTO.setUserRole(String.valueOf(role));
            }else {
               /* if(BusiEnumDefine.USER_ROLE_CEO==userRole||BusiEnumDefine.USER_ROLE_CHRO==userRole||BusiEnumDefine.USER_ROLE_SALARY_CHARGER==userRole){
                    SdUser sdUser = sdUserMapper.selectOne(new QueryWrapper<SdUser>().eq("user_role", userRole));
                    if(!StringUtils.isEmpty(sdUser)){
                        throw new AppBusinessException("当前设置的用户角色已经存在，请设置该用户为其他角色！");
                    }
                }else {*/
                throw new AppBusinessException("请正确填写工号："+userId+"的权限角色！");
                    //}
            }

            Date currentTime = new Date();
            sdUserDTO.setOperateTime(currentTime);
            sdUserDTO.setOperatorId(commService.getLoginUserNameAndId());
            if(!userIdList.contains(jsonObject.get("userId").toString())){
                sdUserDTO.setCreatorId(commService.getLoginUserNameAndId());
            }
            sdUserDTOS.add(sdUserDTO);
        }

        for (SdUserDTO sdUserDTO : sdUserDTOS) {
            if(userIdList.contains(sdUserDTO.getUserId())){
                sdUsersdDTOUpdate.add(sdUserDTO);
            }else {
                sdUsersDTOInsert.add(sdUserDTO);
            }
        }
        List<SdUser> sdUserInsertList= JSONArray.parseArray(JSONArray.toJSONString(sdUsersDTOInsert), SdUser.class);
        List<SdUser> sdUserUpdateList= JSONArray.parseArray(JSONArray.toJSONString(sdUsersdDTOUpdate), SdUser.class);

        int updateNum=0;
        int insertNum=0;
        //日志
        for (SdUser sdUser : sdUserUpdateList) {
            updateNum=updateNum+ sdUserMapper.updateSdUser(sdUser);
            commService.recordAuthChangeLog("sd_user", AutoOpTypeEnum.UPDATE,JSONObject.toJSONString(sdUser),"通过导入更新用户");
        }
        for (SdUser sdUser : sdUserInsertList) {
            insertNum=insertNum+ sdUserMapper.insertSdUser(sdUser);
            commService.recordAuthChangeLog("sd_user", AutoOpTypeEnum.UPDATE,JSONObject.toJSONString(sdUser),"通过导入新建用户");
        }
        return updateNum+insertNum;
    }

    @Override
    public String getUserIdByRoleId(int userRole) {
        List<SdUser> users = list(new LambdaQueryWrapper<SdUser>().eq(SdUser::getUserRole, userRole));
        return users.stream().map(SdUser::getUserId).collect(Collectors.joining(","));
    }

    /**
     * @title: download
     * @description: 用户权限导出
     * @params:
     * @return: File
     * @createTime: 2022-01-26
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public File download(SdUserDTO paramsDTO, String templateCode, String fileName) {
        List<SdUserDTO> sdUserDTOS=selectFuzzyByDto(paramsDTO);
        for (SdUserDTO sdUserDTO:sdUserDTOS){
            StringBuffer roleCh = new StringBuffer();
            String userRole=sdUserDTO.getUserRole();
            for (String role : userRole.split(",")) {
                if(Integer.valueOf(role)== BusiEnumDefine.USER_ROLE_ADMIN){
                    roleCh.append("管理员 ");
                }else if(Integer.valueOf(role)== BusiEnumDefine.USER_ROLE_BP){
                    roleCh.append("HRBP ");
                }else if(Integer.valueOf(role)== BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR){
                    roleCh.append("部门接口人 ");
                }else if(Integer.valueOf(role)== BusiEnumDefine.USER_ROLE_DEPT_MANAGER){
                    roleCh.append("部门主管 ");
                }else if(Integer.valueOf(role)== BusiEnumDefine.USER_ROLE_GBBZ){
                    roleCh.append("干部部长 ");
                }else if(Integer.valueOf(role)== BusiEnumDefine.USER_ROLE_TASK_MANAGER){
                    roleCh.append("小任务管理员 ");
                } else if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_OFFER_SSC_MANAGER){
                    roleCh.append("入职审核ssc管理员 ");
                } else if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_OFFER_DEPT_MANAGER){
                    roleCh.append("入职审核部门管理员 ");
                } else if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_NEW_WORKER_BP){
                    roleCh.append("新员工bp ");
                } else if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_OFFER_BP){
                    roleCh.append("入职期bp ");
                } else if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_CARD_DEPT){
                    roleCh.append("卡证科管理员 ");
                } else if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_RECRUITMENT){
                    roleCh.append("招聘管理员 ");
                } else if (Integer.valueOf(role) == BusiEnumDefine.USER_ROLE_SS_MANAGER) {
                    roleCh.append("社保管理员 ");
                }
            }
            sdUserDTO.setUserRoleCh(roleCh.toString());
        }
        return commService.generateExportFile(fileName, templateCode, (List)sdUserDTOS);
    }

    /**
     * @title: deleteDto
     * @description:批量删除
     * @params:List<SdUserDTO> dtos
     * @return: File
     * @createTime: 2022-01-26
     * @version: 1.0
     * @author: j26296
     */
    @Override
    public Integer deleteDto(List<SdUserDTO> dtos) {
        int i = 0;
        if(dtos != null && dtos.size() > 0){
            for(SdUserDTO dto : dtos){
                if (null != dto && null != dto.getUserId() && !"".equals(dto.getUserId())) {
                    String userId=dto.getUserId();
                    String oldUserRole=dto.getUserRole();
                    //SdUser sdUserOld = sdUserMapper.selectOne(new QueryWrapper<SdUser>().eq("user_id", userId));
//                    List<SdDept> sdDepts= sdDeptMapper.selectList(new QueryWrapper<SdDept>().like("bp_user_id",userId).or()
//                            .like("gbbz_id",userId).or()
//                            .like("level_one_leader_id",userId));
                    for (String role : oldUserRole.split(",")) {
                        if(Integer.valueOf(role)==BusiEnumDefine.USER_ROLE_BP||Integer.valueOf(role)==BusiEnumDefine.USER_ROLE_DEPT_CONTACTOR||Integer.valueOf(role)==BusiEnumDefine.USER_ROLE_DEPT_MANAGER){//别的角色可改
                            String authDeptS = redisTemplate.opsForValue().get(deptRedis + userId);
                            if (!StringUtils.isEmpty(authDeptS)) {
                                throw new AppBusinessException("[工号：" + userId + "]的用户已经被设置为某些部门的HRBP、部门接口人、部门主管，不允许修改其当前角色！");
                            }
                        }
                    }
//                    if(sdDepts.size()>0){
//                        throw new AppBusinessException("[工号："+userId+"]的用户已经被设置为某些部门的HRBP、干部部长或一级主管职位，不允许删除！");
//                    }
                    SdUser tcThirdOrg = JSONObject.parseObject(JSON.toJSONString(dto), SdUser.class);
                    i += sdUserMapper.deleteSdUser(tcThirdOrg);
                    //return tcThirdOrgMapper.deleteByPrimaryKey(dto.getId());
                    commService.recordAuthChangeLog("sd_user", AutoOpTypeEnum.DELETE,JSONObject.toJSONString(tcThirdOrg),"删除用户");
                }
            }
        }
        return i;
    }

}
